import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { WorkflowTemplate, WorkflowTemplateDocument } from '../comfy/schemas/workflow-template.schema'
import { CreateTemplateDto, UpdateTemplateDto } from './template.dto'

@Injectable()
export class TemplateService {
    constructor(
        @InjectModel(WorkflowTemplate.name)
        private readonly templateModel: Model<WorkflowTemplateDocument>
    ) { }

    async findAll(query: any) {
        const { page = 1, limit = 10, category, type, search } = query
        const filter: any = {}

        if (category) {
            filter.category = category
        }
        if (type) {
            filter['metadata.type'] = type
        }
        if (search) {
            filter.$or = [
                { name: { $regex: search, $options: 'i' } },
                { description: { $regex: search, $options: 'i' } }
            ]
        }

        const [items, total] = await Promise.all([
            this.templateModel
                .find(filter)
                .skip((page - 1) * limit)
                .limit(limit)
                .exec(),
            this.templateModel.countDocuments(filter)
        ])

        return {
            items,
            total,
            page: +page,
            limit: +limit,
            pages: Math.ceil(total / limit)
        }
    }

    async findOne(id: string) {
        return this.templateModel.findById(id).exec()
    }

    async create(createTemplateDto: CreateTemplateDto) {
        const template = new this.templateModel(createTemplateDto)
        return template.save()
    }

    async update(id: string, updateTemplateDto: UpdateTemplateDto) {
        return this.templateModel
            .findByIdAndUpdate(id, updateTemplateDto, { new: true })
            .exec()
    }

    async remove(id: string) {
        return this.templateModel.findByIdAndDelete(id).exec()
    }
} 